package com.vivid.system.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.vivid.system.domain.User;
import com.vivid.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@CrossOrigin
@RestController
@RequestMapping("/system/tool")
public class ToolController {
    @Autowired
    private IUserService userService;
    private User user;

    /**
     * 登录验证
     */
    @PostMapping("/verifyLogin")
    public AjaxResult verifyLogin(@RequestBody User user, HttpSession session) {
        if(!user.getAccount().equals("")&&!user.getPassword().equals("")){
            List<User> list = userService.selectUserList(user);
            for (User us : list) {
                session.setAttribute("userId", us.getUserId());
                session.setAttribute("account", us.getAccount());
            }
            if(list.size()>0){
                return AjaxResult.success("登录成功！", list);
            }
        }
        return AjaxResult.success("登录失败！");

    }

    /**
     * 接收上传的文件
     * 将MultipartFile转换为File
     *
     * @param multipartFile
     * @return
     */
    public File MultipartFile(MultipartFile multipartFile) {
        File file = null;
        //MultipartFile转换为File
        InputStream ins = null;
        OutputStream os = null;
        try {
            ins = multipartFile.getInputStream();
            file = new File("data/" + multipartFile.getOriginalFilename());//获取文件名
            os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (ins != null) {
                try {
                    ins.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }

    /**
     * 读取txt文件
     */
    public List<List<Float>> readTxt(String filePath) {
        List<List<Float>> lis = new ArrayList<>();
        try {
            File myFile = new File(filePath);//通过字符串创建File类型对象，指向该字符串路径下的文件
            if (myFile.isFile() && myFile.exists()) { //判断文件是否存在
                InputStreamReader Reader = new InputStreamReader(new FileInputStream(myFile), "UTF-8");
                BufferedReader bufferedReader = new BufferedReader(Reader);
                String lineTxt = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    //buffereReader.readLine()按行读取写成字符串
                    lis.add(stringSplit(lineTxt));
                }
                Reader.close();
            } else {
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        return lis;
    }

    /**
     * 分割字符串，以逗号为准
     * return float类型的集合
     */
    public List<Float> stringSplit(String str) {
        List<Float> lis = new ArrayList<>();
        if (str.indexOf(",") != -1) {
            String[] split = str.split(",");
            for (int i = 0; i < split.length; i++) {
                String url = split[i];
                lis.add(Float.parseFloat(url));
            }
        } else if (str.indexOf("，") != -1) {
            String[] split = str.split("，");
            for (int i = 0; i < split.length; i++) {
                String url = split[i];
                lis.add(Float.parseFloat(url));
            }
        } else {
            String[] split = str.split(",");
            for (int i = 0; i < split.length; i++) {
                String url = split[i];
                lis.add(Float.parseFloat(url));
            }
        }
        return lis;
    }

    /**
     * 字符串转日期：yyyy-MM-dd HH:mm:ss
     *
     * @param str
     * @return
     */
    public String StrToDate(String str) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        String result = null;
        try {
            date = format.parse(str);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            result = simpleDateFormat.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }
/**
 * 判断文件路径是否存在，不存在则新建
 */
public void existFile(String modelResultPath){
    File file = new File(modelResultPath);
// 判断文件路径是否存在
    if(!file.exists()) {
// 如果不存在就创建文件
        file.mkdir();
        System.out.println("创建文件路径成功");
    }
    file = new File(modelResultPath);
    if (!file.exists()) {
        try {
            System.out.println("文件不存在：" + modelResultPath);
            file.createNewFile();
            System.out.println("创建文件成功");
        } catch (IOException e) {
            System.out.println("创建文件失败");
            e.printStackTrace();
        }
    }
}
}
